package bundle2name

import com.mongodb.MongoClient
import com.mongodb.MongoWriteException
import com.mongodb.ServerAddress
import org.bson.Document
import java.io.File
import java.nio.file.FileVisitOption
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*

fun main(args: Array<String>) {
    if(args.isEmpty())
        return
    val dir = File(args[0])
    if(!dir.exists() || !dir.isDirectory)
        return
    val mongoUrl = System.getProperty("dbUrl","localhost:7017").split(":")
    val mongoHost = mongoUrl[0]
    val mongoPort = mongoUrl[1].toInt()
    val mongo = MongoClient(ServerAddress(mongoHost,mongoPort))
    val co = mongo.getDatabase("bundlename").getCollection("bn")
    val fs = Files.walk(Paths.get(dir.toURI()))
    fs.forEach {
        val sc = Scanner(it)
        sc.use {
            while(it.hasNext()){
                val l = it.nextLine()
                val la = l.split("\t")
                if(la.size == 2){
                    try {
                        co.insertOne(Document("_id",la[0]).append("name",la[1]))
                    }catch (e:Exception){
                        if (e is MongoWriteException){
                            val we = e.error
                            if(we.code == 11000){
                                println(la[0] + " duplicated")
                            }
                        }

                    }

                }
            }
        }
    }

}